<!-- 弹窗 详情 -->
<script lang="tsx" setup>
import type { FormInstance } from 'element-plus';
import { ElSelectV2 } from 'element-plus';

import FileUpload from '@/components/file-system/file-upload.vue';
import type { FormDescChild } from '@/components/form-desc/form-desc.vue';
import { RISK_HAZARDS_CONTROL_DANGER_STATUS_OPTIONS } from '@/config/enum-options';
import type { WhManagerBsTbRiskHazardsControlSaveOrUpdateUsingPostBody } from '@/genapi/wh';
import { whManagerBsTbRiskHazardsControlSaveOrUpdateUsingPost } from '@/genapi/wh';
import { useAsync } from '@/hooks/use-async';
import { useCompanyStore } from '@/stores/company';

import { injectState } from '../state';

defineOptions({ name: 'DetailDialog' });

const companyStore = useCompanyStore();

const { page } = injectState()!;

const dialogRef = shallowRef<InstanceType<GlobalComponents['PromiseDialog']>>();

const formRef = shallowRef<FormInstance>();

const dialogType = ref<'add' | 'edit' | 'detail' | string>();

const titleMap: Record<string, string> = {
  add: '新增风险',
  edit: '编辑风险',
  detail: '风险详情',
};

const beforeClose = async () => {
  if (dialogType.value !== 'detail') {
    await ElMessageBox.confirm('确认关闭？');
  }
};

const trigger = async (type = 'add', value = {} as any) => {
  dialogType.value = type;
  model.value = JSON.parse(JSON.stringify(value)) as any;
  await dialogRef.value?.open();
};

defineExpose({
  trigger,
});

const model = ref<WhManagerBsTbRiskHazardsControlSaveOrUpdateUsingPostBody>({} as any);

const file = computed({
  get() {
    if (model.value.dailyCheckFileId) {
      return [
        {
          id: model.value.dailyCheckFileId,
          name: model.value.dailyCheckFileName,
        },
      ];
    }
  },
  set(value: any) {
    model.value.dailyCheckFileId = value?.[0]?.id;
    model.value.dailyCheckFileName = value?.[0]?.name;
  },
});

const { execute, isLoading } = useAsync(async () => {
  await formRef.value?.validate();
  await ElMessageBox.confirm('确认提交？', '提示', {
    type: 'warning',
  });
  console.log(model.value)
  await whManagerBsTbRiskHazardsControlSaveOrUpdateUsingPost({
    data: {
      ...model.value,
      enterpriseId: companyStore.currentCompanyId,
    },
  });
  page.execute();
  ElMessage.success('提交成功');
  dialogRef.value?.complete();
});

const formDescRef = shallowRef<InstanceType<GlobalComponents['FormDesc']>>();

const children: FormDescChild[] = [
  {
    label: '责任人员',
    prop: 'responsiblePerson',
    // rule: [{ required: true, message: '请输入责任人责任人员', trigger: 'blur' }],
    span: 1,
    formItem: () => (
      <ElInput
        v-model={model.value.masterName}
        clearable
        placeholder="请输入责任人责任人员"
      />
    ),
    descItem: () => model.value.masterName || '-',
  },
  {
    label: '责任人联系电话',
    prop: 'masterPhone',
    // rule: [{ required: true, message: '请输入责任人联系电话', trigger: 'blur' }],
    span: 1,
    formItem: () => (
      <ElInput v-model={model.value.masterPhone} clearable placeholder="请输入责任人联系电话" />
    ),
    descItem: () => model.value.connectPhone || '-',
  },

  {
    label: '风险状态',
    prop: 'dangerStatus',
    // rule: [{ required: true, message: '请输入典型工艺', trigger: 'blur' }],
    span: 2,
    formItem: () => (
      <ElSelectV2
        options={[...RISK_HAZARDS_CONTROL_DANGER_STATUS_OPTIONS]}
        v-model={model.value.dangerStatus}
        clearable
        placeholder="请选择风险状态"
      />
    ),
    descItem: () => model.value.dangerStatus || '-',
  },
  {
    label: '风险描述',
    prop: 'dangerDesc',
    // rule: [{ required: true, message: '请输入安全控制要求', trigger: 'blur' }],
    span: 2,
    formItem: () => (
      <ElInput
        v-model={model.value.dangerDesc}
        clearable
        type="textarea"
        placeholder="请输入风险描述"
      />
    ),
    descItem: () => model.value.dangerDesc || '-',
  },
  {
    label: '管控措施',
    prop: 'handleDesc',
    // rule: [{ required: true, message: '请输入安全控制要求', trigger: 'blur' }],
    span: 2,
    formItem: () => (
      <ElInput
        v-model={model.value.handleDesc}
        clearable
        type="textarea"
        placeholder="请输入管控措施"
      />
    ),
    descItem: () => model.value.handleDesc || '-',
  },
  {
    label: '风险日常检查表',
    prop: 'dailyCheckFileName',
    span: 2,
    formItem: () => (
      <FileUpload class="w-100%!" v-model={file.value} limit={1}>
        <el-button type="primary">
          {{
            icon: () => <el-icon class="i-custom:add" />,
            default: () => '上传附件',
          }}
        </el-button>
      </FileUpload>
    ),
    descItem: () => <FileUpload class="w-100%!" v-model={file.value} limit={1} disabled={true} />,
  },
];
</script>

<template>
  <PromiseDialog
    ref="dialogRef"
    :title="titleMap[dialogType!]"
    :before-close="beforeClose"
    max-h="884px!"
    w="707px!"
  >
    <el-scrollbar>
      <FormDesc
        ref="formDescRef"
        :type="dialogType === 'detail' ? 'desc' : 'form'"
        form-class="gap-x-20px"
        :model="model"
        :children="children"
        :column="2"
      />
    </el-scrollbar>
    <template v-if="dialogType !== 'detail'" #footer>
      <el-button @click="dialogRef?.close()">取消</el-button>
      <el-button type="primary" :is-loading="isLoading" @click="execute()">确认</el-button>
    </template>
  </PromiseDialog>
</template>
